package middleware

import (
	"ginblog/utils"
	"ginblog/utils/errmsg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
)

//生成token
var JwtKey = []byte(utils.JwtKey)

var code int

type MyClaims struct {
	Username string `json:"username"`

	jwt.StandardClaims
}

//生成token
func SetToken(username string) (string,int){
	expireTime := time.Now().Add(10 *time.Hour)
	SetCliams := MyClaims{
		username,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer: "ginblog",
		},
	}

	reqClaim := jwt.NewWithClaims(jwt.SigningMethodHS256,SetCliams)
	token,err := reqClaim.SignedString(JwtKey)
	if err != nil {
		return "",errmsg.ERROR
	}
	return token,errmsg.SUCCSE

}

//验证token
func CheckToken(token string) (*MyClaims,int) {
	setToken,_ := jwt.ParseWithClaims(token,&MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return JwtKey,nil
	})
	if setToken==nil {
		return nil,errmsg.ERROR
	}
	if key,_ := setToken.Claims.(*MyClaims);setToken.Valid {
		return key,errmsg.SUCCSE
	}else {
		return nil,errmsg.ERROR
	}
}

//jwt中间件
func JwtToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenHearder := c.Request.Header.Get("Authorization")
		if (tokenHearder == ""||tokenHearder=="Bearer") {
			code = errmsg.ERROR_TOKEN_EXIST
			c.JSON(http.StatusOK,gin.H{
				"code":code,
				"message":errmsg.GetErrMsg(code),
			})
			c.Abort()
			return
		}
		checkToken := strings.SplitN(tokenHearder," ",2)
		if (len(checkToken)!=2&&checkToken[0]!="Bearer") {
			code = errmsg.ERROR_TOKEN_TYPE_WRONG
			c.JSON(http.StatusOK,gin.H{
				"code":code,
				"message":errmsg.GetErrMsg(code),
			})
			c.Abort()
			return
		}
		key,Tcode := CheckToken(checkToken[1])
		if Tcode==errmsg.ERROR {
			code = errmsg.ERROR_TOKEN_WRONG
			c.JSON(http.StatusOK,gin.H{
				"code":code,
				"message":errmsg.GetErrMsg(code),
			})
			c.Abort()
			return
		}
		if time.Now().Unix() > key.ExpiresAt {
			code = errmsg.ERROR_TOKEN_RUNTIME
			c.JSON(http.StatusOK,gin.H{
				"code":code,
				"message":errmsg.GetErrMsg(code),
			})
			c.Abort()
			return
		}

		c.Set("username",key.Username)
		c.Next()
	}
}